package deanandjames.sprite;

import deanandjames.image.ImageLoader;
import deanandjames.image.PlayerImage;

import java.awt.*;
import java.awt.image.BufferedImage;

public class Sprite {
	private static final int SIZE = 12;
	private static final int XSTEP = 5;
	private static final int YSTEP = 5;
	private int height;
	private BufferedImage image;
	private String imageName;
	private final ImageLoader imsLoader;
	private final boolean isActive = true;
	private boolean isLooping;
	private final int panelHeight;
	private final int panelWidth;
	private PlayerImage player;
	private int width;
	protected int dx;
	protected int dy;
	protected int locationX;
	protected int locy;

	public Sprite(int x, int y, int w, int h, ImageLoader imsLd, String name) {
		locationX = x;
		locy = y;
		panelWidth = w;
		panelHeight = h;
		dx = XSTEP;
		dy = YSTEP;
		imsLoader = imsLd;
		setImage(name);
	}

	public void drawSprite(Graphics g) {
		if (isActive()) {
			if (image == null) {
				g.setColor(Color.yellow);
				g.fillOval(locationX, locy, SIZE, SIZE);
				g.setColor(Color.black);
			} else {
				if (isLooping) {
					image = player.getCurrentImage();
				}
				g.drawImage(image, locationX, locy, null);
			}
		}
	}

	public int getHeight() {
		return height;
	}

	public Rectangle getMyRectangle() {
		return new Rectangle(locationX, locy, width, height);
	}

	public int getPanelHeight() {
		return panelHeight;
	}

	public int getPanelWidth() {
		return panelWidth;
	}

	public int getWidth() {
		return width;
	}

	public int getXPosition() {
		return locationX;
	}

	public int getXStep() {
		return dx;
	}

	public int getYPosition() {
		return locy;
	}

	public int getYStep() {
		return dy;
	}

	public boolean isActive() {
		return isActive;
	}

	public void loopImage(int animPeriod, double seqDuration) {
		if (imsLoader.numImages(imageName) > 1) {
			player = null;
			player = new PlayerImage(imageName, animPeriod, seqDuration, true, imsLoader);
			isLooping = true;
		} else {
			System.out.println(imageName + " is not a sequence of images");
		}
	}

	public void setImage(String name) {
		imageName = name;
		image = imsLoader.getImage(imageName);
		if (image == null) {
			System.out.println("No sprite image for " + imageName);
			width = SIZE;
			height = SIZE;
		} else {
			width = image.getWidth();
			height = image.getHeight();
		}
		player = null;
		isLooping = false;
	}

	public void setPosition(int x, int y) {
		locationX = x;
		locy = y;
	}

	public void setStep(int dx, int dy) {
		this.dx = dx;
		this.dy = dy;
	}

	public void stopLooping() {
		if (isLooping) {
			player.stop();
			isLooping = false;
		}
	}

	public void translate(int xDist, int yDist) {
		locationX += xDist;
		locy += yDist;
	}

	public void updateSprite() {
		if (isActive()) {
			locationX += dx;
			locy += dy;
			if (isLooping) {
				player.update();
			}
		}
	}
}
